package com.boc.ewr.business.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.boc.ewr.business.entity.vo.ProChgExportVo;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import com.boc.ewr.business.entity.ProtocolChangeApply;
import com.boc.ewr.business.service.IProtocolChangeApplyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 协议变更申请
 * @Author: jeecg-boot
 * @Date: 2023-04-20
 * @Version: V1.0
 */
@Api(tags = "协议变更申请")
@RestController
@RequestMapping("/business/protocolChangeApply")
@Slf4j
public class ProtocolChangeApplyController extends JeecgController<ProtocolChangeApply, IProtocolChangeApplyService> {
    @Autowired
    private IProtocolChangeApplyService protocolChangeApplyService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param protocolChangeApply
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "协议变更申请-分页列表查询")
    @ApiOperation(value = "协议变更申请-分页列表查询", notes = "协议变更申请-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ProtocolChangeApply>> queryPageList(ProtocolChangeApply protocolChangeApply,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<ProtocolChangeApply> queryWrapper = QueryGenerator.initQueryWrapper(protocolChangeApply, req.getParameterMap());
        Set<String> orgCodeSetByLoginUser = sysBaseAPI.getOrgCodeSetByLoginUser(this.getLoginUser());
        if (orgCodeSetByLoginUser != null) {
            queryWrapper.in("signed_org", orgCodeSetByLoginUser);
        }
        Page<ProtocolChangeApply> page = new Page<ProtocolChangeApply>(pageNo, pageSize);
        IPage<ProtocolChangeApply> pageList = protocolChangeApplyService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param protocolChangeApply
     * @return
     */
    @AutoLog(value = "协议变更申请-添加")
    @ApiOperation(value = "协议变更申请-添加", notes = "协议变更申请-添加")
    //@RequiresPermissions("com.boc.ewr:protocol_change_apply:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ProtocolChangeApply protocolChangeApply) {
        protocolChangeApplyService.save(protocolChangeApply);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param protocolChangeApply
     * @return
     */
    @AutoLog(value = "协议变更申请-编辑")
    @ApiOperation(value = "协议变更申请-编辑", notes = "协议变更申请-编辑")
    //@RequiresPermissions("com.boc.ewr:protocol_change_apply:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ProtocolChangeApply protocolChangeApply) {
        protocolChangeApplyService.updateById(protocolChangeApply);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "协议变更申请-通过id删除")
    @ApiOperation(value = "协议变更申请-通过id删除", notes = "协议变更申请-通过id删除")
    //@RequiresPermissions("com.boc.ewr:protocol_change_apply:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        protocolChangeApplyService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "协议变更申请-批量删除")
    @ApiOperation(value = "协议变更申请-批量删除", notes = "协议变更申请-批量删除")
    //@RequiresPermissions("com.boc.ewr:protocol_change_apply:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.protocolChangeApplyService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "协议变更申请-通过id查询")
    @ApiOperation(value = "协议变更申请-通过id查询", notes = "协议变更申请-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ProtocolChangeApply> queryById(@RequestParam(name = "id", required = true) String id) {
        ProtocolChangeApply protocolChangeApply = protocolChangeApplyService.getById(id);
        if (protocolChangeApply == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(protocolChangeApply);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param protocolChangeApply
     */
    //@RequiresPermissions("com.boc.ewr:protocol_change_apply:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ProtocolChangeApply protocolChangeApply) {
        // 协议变更 导出表 的表头 客户基本信息（不需要包含账户信息），和变更时间，其他变更具体内容不需要展示
        // Step.1 组装查询条件
        QueryWrapper<ProtocolChangeApply> queryWrapper = QueryGenerator.initQueryWrapper(protocolChangeApply, request.getParameterMap());
        LoginUser sysUser = this.getLoginUser();

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        // Step.2 获取导出数据
        List<ProtocolChangeApply> sourceList = service.list(queryWrapper);
        List<ProChgExportVo> exportList = sourceList.stream()
                .map(protocolChangeApplyToConvert -> {
                    ProChgExportVo proChgExportVo = new ProChgExportVo();
                    // 将 ProtocolChangeApply 中的其他属性转换为 ProtocolChangeApplyVo 中的属性
                    BeanUtils.copyProperties(protocolChangeApplyToConvert, proChgExportVo);
                    return proChgExportVo;
                })
                .collect(Collectors.toList());

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        String title = "协议变更申请";
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, ProChgExportVo.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("protocol_change_apply:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ProtocolChangeApply.class);
    }

    private LoginUser getLoginUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser;
    }
}
